/***************************************************************************************
 The copyright in this software is being made available under the BSD License, included
 below. This software may be subject to other third party rights,including patent rights,
 and no such rights are granted under this license.

 Regents of the Tsinghua University, Peking University, Zhejiang University, HKUST
 Tsinghua University, Peking University, Zhejiang University, HKUST 2011

 Copyright (c) 2011, Regents of the Tsinghua University, Peking University, Zhejiang
 University, HKUST. All Rights Reserved.

 Redistribution and use in source and binary forms, with or without modification, are
 permitted provided that the following conditions are met:
   * Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   * Neither the names of the copyright holders nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 OF SUCH DAMAGE.
***************************************************************************************/

/*
*************************************************************************************
* File name:
* Function:
*
*************************************************************************************
*/
#include <stdlib.h>
#include <string.h>
#include "global.h"
extern const byte QP_SCALE_CR[64] ;

/*********************************************************************************************************/

#define  IClip( Min, Max, Val) (((Val)<(Min))? (Min):(((Val)>(Max))? (Max):(Val)))
#define  pel_t  byte
#define  max_pel_value 0xFF

byte ALPHA_TABLE[64] =
{
    0, 0, 0, 0, 0, 0, 1, 1,
    1, 1, 1, 2, 2, 2, 3, 3,
    4, 4, 5, 5, 6, 7, 8, 9,
    10,11,12,13,15,16,18,20,
    22,24,26,28,30,33,33,35,
    35,36,37,37,39,39,42,44,
    46,48,50,52,53,54,55,56,
    57,58,59,60,61,62,63,64
};
byte  BETA_TABLE[64]  =
{
    0, 0, 0, 0, 0, 0, 1, 1,
    1, 1, 1, 1, 1, 2, 2, 2,
    2, 2, 3, 3, 3, 3, 4, 4,
    4, 4, 5, 5, 5, 5, 6, 6,
    6, 7, 7, 7, 8, 8, 8, 9,
    9,10,10,11,11,12,13,14,
    15,16,17,18,19,20,21,22,
    23,23,24,24,25,25,26,27
};
byte CLIP_TAB[64] =
{
    0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 2, 2,
    2, 2, 2, 2, 2, 2, 3, 3,
    3, 3, 3, 3, 3, 4, 4, 4,
    5, 5, 5, 6, 6, 6, 7, 7,
    7, 7, 8, 8, 8, 9, 9, 9
} ;


void GetStrength( byte Strength[2],macroblock_t* MbP,macroblock_t* MbQ,int dir,int edge,int block_y,int block_x );
void EdgeLoop( pel_t* SrcPtr,byte Strength[2],int QP,  int dir,int width,int Chro );
void DeblockMb( image_t *img, pel_t **imgY, pel_t ***imgUV, int blk_y, int blk_x ) ;
void DeblockFrame( image_t *img, pel_t **imgY, pel_t ***imgUV );

/*
*************************************************************************
* Function:The main MB-filtering function
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

void CopyAndDeblockFrame( image_t *img, pel_t **bufY, pel_t ***bufUV, pel_t **imgY, pel_t ***imgUV )
{
    int i;

    for( i = 0; i < img->height; i ++ )
        memcpy( bufY[i], imgY[i], img->width );
    for( i = 0; i < img->height_cr; i ++ )
    {
        memcpy( bufUV[0][i], imgUV[0][i], img->width_cr );
        memcpy( bufUV[1][i], imgUV[1][i], img->width_cr );
    }

    DeblockFrame( img, bufY, bufUV );
}

void DeblockFrame( image_t *img, pel_t **imgY, pel_t ***imgUV )
{
    int mb_x, mb_y ;
    img->current_mb_nr = -1;
    for( mb_y=0 ; mb_y<( img->height>>4 ) ; mb_y++ )
    {
        for( mb_x=0 ; mb_x<( img->width>>4 ) ; mb_x++ )
        {
            img->current_mb_nr++;
            DeblockMb( img, imgY, imgUV, mb_y, mb_x ) ;
        }
    }
}

/*
*************************************************************************
* Function: Deblocks one macroblock
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

void DeblockMb( image_t *img, pel_t **imgY, pel_t ***imgUV, int mb_y, int mb_x )
{
    int           EdgeCondition;
    int           dir,edge,QP;
    byte          Strength[2];
    short         stre; 
    pel_t           *SrcY, *SrcU = NULL, *SrcV = NULL;
    macroblock_t    *MbP, *MbQ ;
    int QPchroma;

    SrcY = imgY    [mb_y<<4] + ( mb_x<<4 ) ;                                                    // pointers to source
    if ( imgUV != NULL )
    {
        SrcU = imgUV[0][mb_y<<3] + ( mb_x<<3 ) ;
        SrcV = imgUV[1][mb_y<<3] + ( mb_x<<3 ) ;
    }
    MbQ  = &mb_data[mb_y*( img->width>>4 ) + mb_x] ;                                               // current Mb

    //if (MbQ->lf_disable) return;


    for( dir=0 ; dir<2 ; dir++ )                                             // vertical edges, than horicontal edges
    {
        EdgeCondition = ( dir && mb_y ) || ( !dir && mb_x )  ;                 // can not filter beyond frame boundaries

        for( edge=0 ; edge<2 ; edge++ )                                          // first 4 vertical strips of 16 pel
        {
            // then  4 horicontal
            if( edge || EdgeCondition )
            {
                MbP = ( edge )? MbQ : ( ( dir )? ( MbQ -( img->width>>4 ) )  : ( MbQ-1 ) ) ; // MbP = Mb of the remote 4x4 block
                QP = ( MbP->qp + MbQ->qp+1 ) >> 1 ;                                  // Average QP of the two blocks
                GetStrength( Strength, MbP, MbQ, dir, edge, mb_y<<2, mb_x<<2 );      // Strength for 4 pairs of blks in 1 stripe

                stre = Strength[0] + Strength[1] * 256; 
                if( stre )                           // only if one of the 4 Strength bytes is != 0
                {
                    EdgeLoop( SrcY + ( edge<<3 )* ( ( dir )? img->width:1 ), Strength,QP,dir, img->width, 0 );
                    if( ( imgUV != NULL ) && !( edge & 1 ) )
                    {
                        QPchroma=( QP_SCALE_CR[MbP->qp]+QP_SCALE_CR[MbQ->qp]+1 )/2;

                        EdgeLoop( SrcU +  ( edge<<2 ) * ( ( dir )? img->width_cr:1 ), Strength, QPchroma, dir, img->width_cr, 1 ) ;
                        EdgeLoop( SrcV +  ( edge<<2 ) * ( ( dir )? img->width_cr:1 ), Strength, QPchroma, dir, img->width_cr, 1 ) ;
                    }
                }
            }
        }//end edge
    }//end loop dir
}


/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
byte BLK_NUM[2][2][2]  = {{{0,8},{2,10}},{{0,2},{8,10}}} ;
void GetStrength( byte Strength[2],macroblock_t* MbP,macroblock_t* MbQ,int dir,int edge,int block_y,int block_x )
{
    int    blkQ, idx ;
    int    blk_x, blk_x2, blk_y, blk_y2 ;
    int    blk_idx, blk_idx2;

    for( idx=0 ; idx<2 ; idx++ )
    {
        blkQ = BLK_NUM[dir][edge][idx] ;
        blk_y = ( block_y + ( blkQ>>2 ) )>>1;
        blk_x = ( ( block_x + ( blkQ&3 ) )>>1 );
        blk_idx = ( ( blk_y&1 )<<1 ) | ( blk_x&1 );

        blk_y2 = blk_y -  dir ;
        blk_x2 = blk_x - !dir ;
        blk_idx2 = ( ( blk_y2&1 )<<1 ) | ( blk_x2&1 );

        if( ( MbP->mb_type==I8MB ) || ( MbQ->mb_type==I8MB ) ) //mdou I4MB->I8MB //xuyan
            Strength[idx] = 2;
        else if( ( MbQ->mb_type==INTER8x8 && ( MbQ->subblock_type[blk_idx ] == SUBBLOCK_INTRA8x8
                                               || MbQ->subblock_type[blk_idx ] == SUBBLOCK_INTRA4x4 ) )
                 ||  ( MbP->mb_type==INTER8x8 && ( MbP->subblock_type[blk_idx2] == SUBBLOCK_INTRA8x8
                         || MbP->subblock_type[blk_idx2] == SUBBLOCK_INTRA4x4 ) ) )
            Strength[idx] = 2;
        else if( ( MbQ->mb_type==INTER8x8 && MbQ->subblock_type[blk_idx ] == SUBBLOCK_INTER4x4 )
                 ||  ( MbP->mb_type==INTER8x8 && MbP->subblock_type[blk_idx2] == SUBBLOCK_INTER4x4 ) )
            Strength[idx] = 0;

        else if( img->type==P_IMG )
            Strength[idx] = ( abs( frm_mv[MAX_REF_NUM][blk_y][blk_x].x - frm_mv[MAX_REF_NUM][blk_y2][blk_x2].x ) >= 2 ) |
                            ( abs( frm_mv[MAX_REF_NUM][blk_y][blk_x].y - frm_mv[MAX_REF_NUM][blk_y2][blk_x2].y ) >= 2 );
        else
            Strength[idx] = ( abs( frm_bi_mv[blk_y][blk_x].fw_mv.x - frm_bi_mv[blk_y2][blk_x2].fw_mv.x ) >= 2 )|
                            ( abs( frm_bi_mv[blk_y][blk_x].fw_mv.y - frm_bi_mv[blk_y2][blk_x2].fw_mv.y ) >= 2 ) |
                            ( abs( frm_bi_mv[blk_y][blk_x].bw_mv.x - frm_bi_mv[blk_y2][blk_x2].bw_mv.x ) >= 2 ) |
                            ( abs( frm_bi_mv[blk_y][blk_x].bw_mv.y - frm_bi_mv[blk_y2][blk_x2].bw_mv.y ) >= 2 );
    }
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void EdgeLoop( pel_t* SrcPtr,byte Strength[2],int QP, int dir,int width,int Chro )
{
    int      pel, ap, aq, PtrInc, Strng ;
    int      inc, inc2, inc3 ;
    int      C0, Delta, dif, AbsDelta ;
    int      L2, L1, L0, R0, R1, R2, RL0 ;
    int      Alpha, Beta ;
    int          small_gap;

    PtrInc  = dir?  1 : width ;
    inc     = dir?  width : 1 ;
    inc2    = inc<<1 ;
    inc3    = inc + inc2 ;

    Alpha = ALPHA_TABLE[RFM_CLIP3( QP+alpha_offset,0,63 )];

    Beta = BETA_TABLE[RFM_CLIP3( QP+beta_offset,0,63 )];

    for( pel=0 ; pel<16 ; pel++ )
    {
        if( ( Strng = Strength[pel >> 3] ) )
        {
            L2  = SrcPtr[-inc3] ;
            L1  = SrcPtr[-inc2] ;
            L0  = SrcPtr[-inc ] ;
            R0  = SrcPtr[    0] ;
            R1  = SrcPtr[ inc ] ;
            R2  = SrcPtr[ inc2] ;
            AbsDelta = abs( Delta = R0 - L0 ) ;
            if( AbsDelta < Alpha )
            {
                if( ( abs( R0 - R1 ) < Beta ) && ( abs( L0 - L1 ) < Beta ) )
                {
                    aq = ( abs( R0 - R2 ) < Beta ) ;
                    ap = ( abs( L0 - L2 ) < Beta ) ;
                    if( Strng == 2 )
                    {
                        RL0 = L0 + R0 ;
                        small_gap = ( AbsDelta < ( ( Alpha >> 2 ) + 2 ) );
                        aq &= small_gap;
                        ap &= small_gap;

                        SrcPtr[   0 ] = aq ? ( R1 + RL0 +  R0 + 2 ) >> 2 : ( ( R1 << 1 ) + R0 + L0 + 2 ) >> 2 ;
                        SrcPtr[-inc ] = ap ? ( L0 +  L1 + RL0 + 2 ) >> 2 : ( ( L1 << 1 ) + L0 + R0 + 2 ) >> 2 ;

                        SrcPtr[ inc ] = ( aq && !Chro ) ? ( R0 + R1 + L0 + R1 + 2 ) >> 2 : SrcPtr[ inc ];
                        SrcPtr[-inc2] = ( ap && !Chro ) ? ( L1 + L1 + L0 + R0 + 2 ) >> 2 : SrcPtr[-inc2];
                    }
                    else    //Strng == 1
                    {
                        C0  = CLIP_TAB[RFM_CLIP3( QP+alpha_offset,0,63 )] ;
                        dif             = IClip( -C0, C0, ( ( R0 - L0 ) * 3 + ( L1 - R1 ) + 4 ) >> 3 ) ;
                        SrcPtr[  -inc ] = IClip( 0, max_pel_value, L0 + dif ) ;
                        SrcPtr[     0 ] = IClip( 0, max_pel_value, R0 - dif ) ;
                        if( !Chro )
                        {
                            L0 = SrcPtr[-inc] ;
                            R0 = SrcPtr[   0] ;
                            if( ap )
                            {
                                dif           = IClip( -C0, C0, ( ( L0 - L1 ) * 3 + ( L2 - R0 ) + 4 ) >> 3 ) ;
                                SrcPtr[-inc2] = IClip( 0, max_pel_value, L1 + dif ) ;
                            }
                            if( aq )
                            {
                                dif           = IClip( -C0, C0, ( ( R1 - R0 ) * 3 + ( L0 - R2 ) + 4 ) >> 3 ) ;
                                SrcPtr[ inc ] = IClip( 0, max_pel_value, R1 - dif ) ;
                            }
                        }
                    }
                }
            }
            SrcPtr += PtrInc ;
            pel    += Chro ;
        }
        else
        {
            SrcPtr += PtrInc << ( 3 - Chro ) ;
            pel    += 7 ;
        }  ;
    }
}
